package com.star.robot.controller;

import com.github.qcloudsms.SmsSingleSenderResult;
import com.star.robot.constant.Constant;
import com.star.robot.dto.AdminRequestDto;
import com.star.robot.dto.RegRequestDto;
import com.star.robot.dto.ResultDto;
import com.star.robot.entity.Admin;
import com.star.robot.entity.User;
import com.star.robot.repository.AdminRepositoty;
import com.star.robot.repository.UserRepositoty;
import com.star.robot.service.SmsService;
import com.star.robot.service.UserService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.web.PageableDefault;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 管理员管理
 */
@RestController
@RequestMapping(value = "/user")
public class UserController {

    @Autowired
    private UserRepositoty userRepositoty;

    @Autowired
    AdminRepositoty adminRepositoty;

    @Autowired
    private UserService userService;


    @ApiOperation(value = "用户注册",notes="用户注册")
    @PostMapping(value = "/reg")
    public ResultDto reg(@RequestBody  RegRequestDto requestDto, HttpServletRequest request){
        validateParam(requestDto,request);

        User user = new User();
        BeanUtils.copyProperties(requestDto , user);
        user.setPasswd(user.getPasswd());
        userRepositoty.save(user);
        return ResultDto.builder().build();
    }

    /**
     * 单位用户登录
     * @param requestDto
     * @param request
     * @return
     */
    @ApiOperation(value = "用户登录",notes="")
    @PostMapping(value = "/login")
    public ResultDto login(@RequestBody  RegRequestDto requestDto , HttpServletRequest request){
        validLoginParam(requestDto);
        User user = userRepositoty.findByPhoneAndPasswd(requestDto.getPhone() , requestDto.getPasswd());
        if(user != null){
            //session绑定手机号
            request.getSession().setAttribute(Constant.CURRENTUSER, user);
            return ResultDto.builder().build();
        }else{
            return ResultDto.builder().success(Boolean.FALSE).build();
        }

    }

    /**
     * 管理用户登录
     * @param requestDto
     * @param request
     * @return
     */
//    @ApiOperation(value = "管理用户登录",notes="")
//    @PostMapping(value = "/adminLogin")
//    public ResultDto adminLogin(@RequestBody AdminRequestDto requestDto , HttpServletRequest request){
//        validLoginParam(requestDto);
//
//        Admin user = adminRepositoty.findByUsernameAndPasswd(requestDto.getUsername() , requestDto.getPasswd());
//        if(user != null){
//            //session绑定手机号
//            request.getSession().setAttribute(Constant.CURRENTUSER, requestDto.getUsername());
//            return ResultDto.builder().build();
//        }else{
//            return ResultDto.builder().success(Boolean.FALSE).build();
//        }
//
//    }

    /**
     * 单位用户登录验证
     * @param requestDto
     */
    private void validLoginParam(RegRequestDto requestDto) {
        //手机号必填
        if(StringUtils.isEmpty(requestDto.getPhone())){
            throw new IllegalArgumentException("手机号必填");
        }
        //密码必填
        if(StringUtils.isEmpty(requestDto.getPasswd())){
            throw new IllegalArgumentException("密码必填");
        }
    }

    /**
     * 管理用户登录验证
     * @param requestDto
     */
    private void validLoginParam(AdminRequestDto requestDto) {
        //用户名
        if(StringUtils.isEmpty(requestDto.getUsername())){
            throw new IllegalArgumentException("用户名必填");
        }
        //密码必填
        if(StringUtils.isEmpty(requestDto.getPasswd())){
            throw new IllegalArgumentException("密码必填");
        }
    }

    private void validateParam(RegRequestDto requestDto , HttpServletRequest request) {
        if(requestDto == null){
            throw new IllegalArgumentException("注册参数必填");
        }
//        if(StringUtils.isEmpty(requestDto.getVerfiCode())){
//            throw new IllegalArgumentException("验证码必填");
//        }
//        if(request.getSession().getAttribute("VERIFYCODE") == null
//                || request.getSession().getAttribute("VERIFYCODE").equals(requestDto.getVerfiCode())){
//            throw new IllegalArgumentException("短信验证码不正确");
//        }
        //手机号必填
        if(StringUtils.isEmpty(requestDto.getPhone())){
            throw new IllegalArgumentException("手机号必填");
        }
        //验证码必填
//        if(StringUtils.isEmpty(requestDto.getVerfiCode())){
//            throw new IllegalArgumentException("验证码必填");
//        }
        //密码必填
        if(StringUtils.isEmpty(requestDto.getPasswd())){
            throw new IllegalArgumentException("密码必填");
        }
        //区必填
        if(StringUtils.isEmpty(requestDto.getAreaId())){
            throw new IllegalArgumentException("区必填");
        }
        //单位必填
//        if(requestDto.getCompanyId() == null){
//            throw new IllegalArgumentException("单位必填");
//        }

    }


    @ApiOperation(value = "用户查询",notes="用户查询")
    @GetMapping(value = "/")
    public ResultDto get(@PageableDefault Pageable page ,  @RequestBody  RegRequestDto requestDto, HttpServletRequest request){

        Page pagedUser =  userRepositoty.findAll(new Specification<User>() {
            @Override
            public Predicate toPredicate(Root<User> root, CriteriaQuery<?> cq, CriteriaBuilder cb) {
                List<Predicate> predicateList = new ArrayList<>();
                //地区搜索
                if(requestDto.getAreaId() != null){
                    predicateList.add(cb.equal( root.get("areaId") , requestDto.getAreaId()));
                }



                Predicate[] pre = new Predicate[predicateList.size()];

                cq.where(predicateList.toArray(pre));
                return cq.getRestriction();
            }
        }, page);
        return ResultDto.builder().data(pagedUser).build();
    }
    @ApiOperation(value = "修改密码",notes="修改密码")
    @PutMapping(value = "/modifyPassword")
    public ResultDto modifyPassword(  @RequestBody  RegRequestDto requestDto, HttpServletRequest request){
        String phone = userService.getCurrentUsername(request);
        requestDto.setPhone(phone);

        if(StringUtils.isEmpty(requestDto.getPasswd())){
            throw new IllegalArgumentException("密码必填");
        }
        if(StringUtils.isEmpty(requestDto.getNewPass())){
            throw new IllegalArgumentException("新密码必填");
        }
//        if(StringUtils.isEmpty(requestDto.getVerfiCode())){
//            throw new IllegalArgumentException("验证码必填");
//        }
//        //校验验证码
//        Object tempSendCode =request.getSession().getAttribute(Constant.SMS_RESET_PASSWD_FLAG ) ;
//        String sendCode = tempSendCode != null ? String.valueOf(tempSendCode):"";
//        if(StringUtils.isEmpty(sendCode)){
//            throw new IllegalArgumentException("请点击发送验证码");
//        }
////        
//        if(!requestDto.getVerfiCode().equals(sendCode)){
//            throw new IllegalArgumentException("验证码不匹配，请重新发送");
//        }
        User user = userRepositoty.findByPhoneAndPasswd(requestDto.getPhone() , requestDto.getPasswd());
        if(user != null){
            user.setPasswd(requestDto.getNewPass());
            user.setModifyPwd(1);
            userRepositoty.save(user);
            return ResultDto.builder().success(true).data(null).build();
        }
        return ResultDto.builder().success(false).message("原密码错误").data(null).build();
    }

    @ApiOperation(value = "用户注册",notes="用户注册")
    @PostMapping(value = "/register")
    public ResultDto register(@RequestBody RegRequestDto regRequestDto,HttpServletRequest request){
        String verfiCode= regRequestDto.getVerfiCode();

        String codeSession = (String) request.getSession().getAttribute(VALIDATE_CODE);
        String phoneSession = (String) request.getSession().getAttribute(SEND_PHONE);
        String phone=regRequestDto.getPhone();

        if (codeSession!=null&&codeSession.equals(verfiCode) && phoneSession.equals(phone)) {
            Date curentTime=new Date();
            Date date = new Date(curentTime.getTime() - 5*60*1000);// 分钟 = 60秒*1000
            Date lastSendTime =(Date) request.getSession().getAttribute(SEND_TIME);
            if (date.before(lastSendTime) && phoneSession.equals(phone)) {
            }

            return userService.reg(regRequestDto, request);

        } else {
            return ResultDto.builder().data(null).code(-1).success(false).message("验证码错误").build();
        }

    }


    private static final String VALIDATE_CODE = "VALIDATE_CODE";
    private static final String SEND_TIME = "SEND_TIME";
    private static final String SEND_PHONE = "SEND_PHONE";

    @ApiOperation(value = "发送验证码",notes="发送验证码")
    @GetMapping(value = "/sms")
    public ResultDto sendSms(String phone,HttpServletRequest request){


        if(!StringUtils.isEmpty(phone)){

            String phoneSession =(String) request.getSession().getAttribute(SEND_PHONE);

            Date curentTime=new Date();
            Date date = new Date(curentTime.getTime() - 60*1000);// 分钟 = 60秒*1000
            Date lastSendTime =(Date) request.getSession().getAttribute(SEND_TIME);

            if (lastSendTime!=null&&date.before(lastSendTime) && phoneSession.equals(phone)) {
                return ResultDto.builder().code(-1).success(false).message("发送验证码频发，稍后再试").build();
            }

//            String code = SmsService.sendMsg(phone);
            String code=SmsService.createCharacter();
            System.out.println("code:--------"+code);

            request.getSession().setAttribute(VALIDATE_CODE, code);
            request.getSession().setAttribute(SEND_TIME, new Date());
            request.getSession().setAttribute(SEND_PHONE, phone);
        }
        return  ResultDto.builder().build();

    }

    private String tt(HttpServletRequest request) {

        request.getSession().getAttribute(VALIDATE_CODE);
        request.getSession().getAttribute(SEND_TIME);
        request.getSession().getAttribute(SEND_PHONE);



        return null;
    }

}
